﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Mengsk.ERP.Orders;
using Mengsk.ERP.Orders.TDOrderInterfaces;

namespace Mengsk.ERP.App.AddressCheck
{
    /// <summary>
    /// DownloadingWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DownloadingWindow : Window
    {
        internal List<Order> Orders { get; private set; }

        internal TDOrderInterfaceBase[] OrderManagers { set { this.models = value.Select(obj => new DownloadViewModel(obj)).ToArray(); } }

        internal OrderDownloadArgs DownloadArgs { get; set; }

        private DownloadViewModel[] models = null;
        private bool hasCancelClicked = false;

        public DownloadingWindow()
        {
            InitializeComponent();
            this.Orders = new List<Order>();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.lstOrderManagers.ItemsSource = this.models;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            foreach (var item in this.models)
            {
                item.Deattach();
                if (!this.hasCancelClicked)
                {
                    this.Orders.AddRange(item.Orders);
                }
            }
            this.DialogResult = !this.hasCancelClicked;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.hasCancelClicked = true;
            foreach (var item in this.models)
            {
                item.OrderManager.StopDownloadOrders();
            }
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            this.hasCancelClicked = false;
            OrderDownloadArgs args = new OrderDownloadArgs
            {
                DownLoadItems = true,
                DwonloadItemsImage = false,
                StartTime = DateTime.Now.AddDays(-7),
                EndTime = DateTime.Now.AddMinutes(10),
                RaiseEvents = true,
                OrderState = "STATE_COD_WAIT_SHIP"
            };
            foreach (var item in this.models)
            {
                item.OrderManager.StartDownloadOrders(this.DownloadArgs != null ? this.DownloadArgs : args);
            }
        }
    }
}
